package com.config;

import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author: create by God of SJF
 * @version: v1.0
 * @description: com.config
 * @date:2021/9/13
 */

@Component
public class StockTableDetailShardingRule extends ShardingDictionaries implements ComplexKeysShardingAlgorithm<String> {

    @Override
    public Collection<String> doSharding(Collection<String> collection, ComplexKeysShardingValue<String> complexKeysShardingValue) {
        String tableIndex = getIndex(complexKeysShardingValue);
        List<String> returnSharding = new ArrayList<>();
        String s = complexKeysShardingValue.getLogicTableName() + tableIndex;
        returnSharding.add(s);
        return returnSharding;
    }


    public String getIndex(ComplexKeysShardingValue<String> complexKeysShardingValue) {
        List<String> list = (List<String>) complexKeysShardingValue.getColumnNameAndShardingValuesMap().get("_barcode_content");
        String finalMap = null;
        String barcodeDirect = list.get(0);
        String first = barcodeDirect.substring(barcodeDirect.length() - 2, barcodeDirect.length() - 1);
        String firstKey = super.key(first);
        String second = barcodeDirect.substring(barcodeDirect.length() - 1, barcodeDirect.length());
        String secondKey = super.key(second);
        StringBuilder sb = new StringBuilder();
        sb.append("_");
        sb.append(secondKey + "_");
        sb.append(firstKey+"_");

        List<String> list2 = (List<String>) complexKeysShardingValue.getColumnNameAndShardingValuesMap().get("_status");
        String status = list2.get(0);
        if (status != null) {
            if (
                    status.equals("1") || status.equals("6")
            ) {
                sb.append("1");
            } else if (status.equals("2") || status.equals("3")) {
                sb.append("2");
            } else {
                sb.append("3");
            }
        }
        finalMap = sb.toString();
        return finalMap;
    }
}
